package com.github.ghsea.kafka;

import org.apache.kafka.clients.producer.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.stereotype.Component;

/**
 * @author guhai
 */
@Component
public class KafkaProduceContext {

    private static KafkaTemplate<String, String> kafkaTemplate;

    private static ThreadLocal<KafkaContextBean> producerThreadLocal = new ThreadLocal<KafkaContextBean>() {
        @Override
        public KafkaContextBean initialValue() {
            ProducerFactory<String, String> producerFactory = kafkaTemplate.getProducerFactory();
            Producer<String, String> producer = producerFactory.createProducer();
            producer.beginTransaction();

            KafkaContextBean kafkaContextBean =new KafkaContextBean();
            kafkaContextBean.setProducer(producer);

            return kafkaContextBean;
        }
    };

    public Producer getProducer() {
        return producerThreadLocal.get().getProducer();
    }

    public static KafkaContextBean getKafkaContextBean() {
        return producerThreadLocal.get();
    }

    public void clear() {
        KafkaContextBean kafkaContextBean = producerThreadLocal.get();
        Producer<String, String> producer = kafkaContextBean.getProducer();
        if (producer != null) {
            producer.close();
        }

        producerThreadLocal.remove();
    }

    @Autowired
    public void setKafkaTemplate(KafkaTemplate<String, String> kafkaTemplate) {
        KafkaProduceContext.kafkaTemplate = kafkaTemplate;
    }

}
